package com.google.code.msgbooster.core;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.google.code.msgbooster.model.Meta;

public final class DB {

	public static boolean delete(PersistenceManager persistenceManager,
			Object object) {
		boolean result = true;
		try {
			persistenceManager.deletePersistent(object);
		} catch (Exception e) {
			result = false;
		}
		return result;
	}

	public static Object make(PersistenceManager persistenceManager,
			Object object) {
		return persistenceManager.makePersistent(object);
	}

	@SuppressWarnings("unchecked")
	public static List<Object> select(PersistenceManager persistenceManager,
			Class<?> cls) {
		List<Object> result = new ArrayList<Object>();
		Query query = persistenceManager.newQuery(cls);
		try {
			result = (List<Object>) query.execute();
		} finally {
			query.closeAll();
		}
		return result;
	}

	public static Object select(PersistenceManager persistenceManager, Meta meta) {
		return DB.select(persistenceManager, meta.getClass(), meta.getKey());
	}

	public static Object select(PersistenceManager persistenceManager,
			Class<?> cls, Key key) {
		return persistenceManager.getObjectById(cls, key);
	}

	public static boolean truncate(PersistenceManager persistenceManager,
			Class<?> cls) {
		boolean result = true;
		Query query = persistenceManager.newQuery(cls);
		try {
			persistenceManager.deletePersistentAll((List<Object>) DB.select(
					persistenceManager, cls));
		} catch (Exception e) {
			result = false;
		} finally {
			query.closeAll();
		}
		return result;
	}

	public static boolean update(PersistenceManager persistenceManager,
			Meta meta) {
		boolean result = true;
		try {
			persistenceManager.makePersistent(meta);
		} catch (Exception e) {
			result = false;
		}
		return result;
	}

}
